package com.pengtu.utils.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.pengtu.entity.app.Attachment;
import com.pengtu.service.app.SystemManager;
import com.pengtu.utils.UploadFile;
import com.pengtu.utils.spring.SpringContextHolder;

/**
 * Servlet implementation class Annex
 */
public class Annex extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Annex() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			//下载附件
			String id = request.getParameter("id");
			if(StringUtils.isNotEmpty(id)){
				SystemManager systemManager =  SpringContextHolder.getBean("systemManager");
				Attachment attachment =  systemManager.getAttachment(id);
				UploadFile.downloadFile(request, response, attachment);
				return ;
			}
			String path = request.getParameter("path");
			if(StringUtils.isNotEmpty(path)){
				String fullPath = getServletContext().getRealPath("/");
				File file = new File(fullPath+"/"+path);
				UploadFile.downloadFileByInputStream(request, response, file);
				return;
			}
			
		}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
